/*
 * @lc app=leetcode.cn id=102 lang=swift
 *
 * [102] 二叉树的层次遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.left = nil
 *         self.right = nil
 *     }
 * }
 */
class Solution102 {
    func levelOrder(_ root: TreeNode?) -> [[Int]] {
        guard let root = root else {
            return []
        }
        var queue: [TreeNode] = [root]
        var result: [[Int]] = []
        while !queue.isEmpty {
            var size = queue.count
            var subArray: [Int] = []
            while size > 0 {
                let e = queue.removeFirst()
                subArray.append(e.val)
                if let left = e.left {
                    queue.append(left)
                }
                if let rigth = e.right {
                    queue.append(rigth)
                }
                size -= 1
            }
            result.append(subArray)
        }
        return result
    }
    static func test() {
        let node3 = TreeNode(3)
        let node9 = TreeNode(9)
        let node20 = TreeNode(20)
        let node15 = TreeNode(15)
        let node7 = TreeNode(7)
        
        node3.left = node9
        node3.right = node20
        node20.left = node15
        node20.right = node7
        let result = Solution102().levelOrder(node3)
        print(result)
    }
}
// @lc code=end

